// headsupdisplay.cpp

// 2008-05-02 11:29:08 (Jake): created

#include "crankit_precompiled.h"
#include "game.h"
#include "headsupdisplay.h"

using namespace std;

HeadsUpDisplay::HeadsUpDisplay(Game* game) : _game(game)
{
	_width = 1600;
	_height = 1200;
}

osg::Node* HeadsUpDisplay::getNode()
{
	if (_camera.valid()) {
		return _camera.get();
	}

	osg::ref_ptr<osg::Camera> camera = new osg::Camera();

    camera->setProjectionMatrix(osg::Matrix::ortho2D(0, _width, 0, _height));
    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    camera->setViewMatrix(osg::Matrix::identity());
    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
    camera->setRenderOrder(osg::Camera::POST_RENDER);
    camera->setAllowEventFocus(false);
	camera->setUpdateCallback(this);

	osg::ref_ptr<osg::Geode> geode = new osg::Geode();
	std::string fontName("fonts/arial.ttf");
    osg::StateSet* stateset = geode->getOrCreateStateSet();
    stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

	{
		osgText::Text* text = new osgText::Text;
		text->setColor(osg::Vec4(1, 1, 1, 1));
        text->setFont(fontName);
		text->setPosition(osg::Vec3(1400, 1120, 0));
		text->setCharacterSize(40);
        text->setText("");
		text->setDataVariance(osg::Object::DYNAMIC);
        geode->addDrawable(text);

		_textTime = text;
	}

	{
		osgText::Text* text = new osgText::Text;
		text->setColor(osg::Vec4(1, 1, 1, 1));
        text->setFont(fontName);
		text->setPosition(osg::Vec3(10, 1120, 0));
		text->setCharacterSize(40);
        text->setText("");
		text->setDataVariance(osg::Object::DYNAMIC);
        geode->addDrawable(text);

		_textCamera = text;
	}

	camera->addChild(geode.get());

	_camera = camera.get();

	return _camera.get();
}

ostream& operator<<(ostream& os, const osg::Vec3& v)
{
	os << "(" << v.x() << ", " << v.y() << ", " << v.z() << ")";

	return os;
}

void HeadsUpDisplay::operator()(osg::Node* node, osg::NodeVisitor* nv)
{
	{
		ostringstream os;
		os << fixed << setprecision(2) << _game->getTime();
		_textTime->setText(os.str());
	}

	{
		ostringstream os;
		osg::Vec3 eye, center, up;
		_game->getCamera()->getViewMatrixAsLookAt(eye, center, up);
		os << fixed << setprecision(2);
		os << "eye " << eye << endl;
		os << "center " << center << endl;
		os << " up " << up;
		_textCamera->setText(os.str());
	}

    traverse(node, nv);
}
